#!/usr/bin/env python3
"""
HR系统UI功能验证脚本
验证前端是否能正确响应后端的UI指令
"""

import requests
import json
import time

def verify_ui_functionality():
    """验证UI功能是否正常工作"""
    
    print("🧪 HR系统UI功能验证")
    print("=" * 50)
    
    base_url = "http://localhost:8089"
    
    # 检查系统状态
    print("📊 检查系统状态...")
    try:
        response = requests.get(f"{base_url}/api/status", timeout=5)
        if response.status_code == 200:
            data = response.json()
            print(f"✅ 系统状态: {data['system_status']}")
            print(f"✅ 候选人数量: {data['candidate_count']}")
            print(f"✅ 系统版本: {data.get('version', 'Unknown')}")
        else:
            print("❌ 系统状态检查失败")
            return False
    except Exception as e:
        print(f"❌ 无法连接到系统: {e}")
        return False
    
    # 测试用例
    test_cases = [
        {
            "name": "筛选Python工程师",
            "message": "筛选会Python的工程师，显示前3个",
            "expected_ui_commands": ["UPDATE_CANDIDATE_LIST"],
            "expected_candidates": True
        },
        {
            "name": "生成面试题",
            "message": "给候选人10751444出一道面试题",
            "expected_ui_commands": ["SHOW_INTERVIEW_QUESTIONS"],
            "expected_candidates": False
        },
        {
            "name": "简单对话",
            "message": "你们的招聘标准是什么？",
            "expected_ui_commands": [],
            "expected_candidates": False
        }
    ]
    
    success_count = 0
    
    for i, test_case in enumerate(test_cases, 1):
        print(f"\n🔍 测试用例 {i}: {test_case['name']}")
        
        try:
            response = requests.post(
                f"{base_url}/api/chat",
                json={"message": test_case["message"]},
                timeout=15
            )
            
            if response.status_code == 200:
                data = response.json()
                
                # 检查基本响应
                if not data.get('success'):
                    print(f"❌ API响应失败: {data.get('error', 'Unknown error')}")
                    continue
                
                # 检查UI指令
                ui_commands = data.get('ui_commands', [])
                expected_commands = test_case['expected_ui_commands']
                
                if expected_commands:
                    command_types = [cmd.get('command') for cmd in ui_commands]
                    if all(expected in command_types for expected in expected_commands):
                        print(f"✅ UI指令正确: {command_types}")
                    else:
                        print(f"❌ UI指令不匹配: 期望{expected_commands}, 实际{command_types}")
                        continue
                else:
                    print(f"✅ 无UI指令（预期）")
                
                # 检查候选人数据
                analyzed_candidates = data.get('analyzed_candidates', [])
                if test_case['expected_candidates']:
                    if len(analyzed_candidates) > 0:
                        print(f"✅ 候选人数据: {len(analyzed_candidates)}个")
                    else:
                        print("❌ 缺少候选人数据")
                        continue
                else:
                    print("✅ 无候选人数据（预期）")
                
                # 检查响应消息
                message = data.get('message', '')
                if len(message) > 10:
                    print(f"✅ AI响应: {message[:50]}...")
                else:
                    print("❌ AI响应过短")
                    continue
                
                print(f"🎉 测试用例 {i} 通过")
                success_count += 1
                
            else:
                print(f"❌ HTTP错误: {response.status_code}")
                
        except Exception as e:
            print(f"❌ 测试失败: {e}")
        
        # 间隔一段时间避免请求过快
        if i < len(test_cases):
            time.sleep(2)
    
    print(f"\n{'='*50}")
    print(f"📊 测试结果: {success_count}/{len(test_cases)} 通过")
    
    if success_count == len(test_cases):
        print("🎉 所有UI功能测试通过！")
        print("\n🌐 手动验证步骤:")
        print("1. 访问: http://localhost:8089/living_workspace.html")
        print("2. 打开浏览器开发者工具 (F12)")
        print("3. 在聊天框中输入以下测试消息:")
        print("   - '筛选会Python的工程师，显示前3个'")
        print("   - '给候选人10751444出一道面试题'")
        print("4. 观察侧边栏候选人卡片更新")
        print("5. 观察面试题模态框弹出")
        print("6. 检查控制台输出UI指令处理日志")
        return True
    else:
        print("❌ 部分测试失败，请检查系统状态")
        return False

if __name__ == "__main__":
    success = verify_ui_functionality()
    exit(0 if success else 1)





